package com.redwine.app;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.CommonListDataResponse;
import com.redwine.app.net.responses.MultipartRequest;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.ActivitySplitAnimationUtil;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.DataCleanManager;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.Settings;
import com.redwine.app.view.AlertDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 个人信息页面
 * 作者：gassion on 17/8/27 17:13
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class PersonalInfoActivity extends BaseActivity {

    @ViewInject(R.id.personal_center_iv_user_photo)
    ImageView personalCenterIvUserPhoto;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.personal_center_tv_clear_cache)
    private TextView tvClearCache;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    private Intent intent;
    private boolean isExitAccount = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_center);
        ViewUtils.inject(this);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        if (null != Global.user) {
            String avatar = Global.user.getAvatar();
            BitmapUtils.loadImage(personalCenterIvUserPhoto, avatar, BitmapUtils.ROUND);
        }
        headerTitle.setText(R.string.personal_info);
        layoutBack.setVisibility(View.VISIBLE);
        getCacheSize(false);
    }

    @OnClick({R.id.layout_back, R.id.personal_center_tv_exit_account, R.id.personal_center_iv_user_photo, R.id.personal_center_ll_basic_information,
            R.id.personal_center_ll_my_collection, R.id.personal_center_ll_shipping_address, R.id.personal_center_ll_update_password, R.id.personal_center_ll_clear_cache,
            R.id.personal_center_ll_about_app, R.id.layout_back})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;
            case R.id.personal_center_tv_exit_account:
                Log.e("params","personal_center_tv_exit_account");
                //关闭主界面进入打开登陆页面
                AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInfoActivity.this);
                builder.setTopImage(R.mipmap.app_icon);
                builder.setMessage(getString(R.string.exit_account));
                builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isExitAccount = true;
                        Settings.logOut();
                        EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.EXIT_ACCOUNT));
                        intent = new Intent(PersonalInfoActivity.this, LoginActivity.class);
                        ActivitySplitAnimationUtil.startActivity(PersonalInfoActivity.this, intent);
                        finish();
                    }
                });
                builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog mDialog = builder.create();
                mDialog.setCancelable(false);
                mDialog.show();
                break;
            case R.id.personal_center_iv_user_photo:
                if (!NetUtil.checkNet(this)) {
                    showToast(R.string.generic_check);
                    return;
                }
                choosePhotoDialog();
                break;

            case R.id.personal_center_ll_basic_information:
                //个人的基本信息页面
                intent = new Intent(PersonalInfoActivity.this, PersonalBasicInformationActivity.class);
                startActivity(intent);
                break;

            case R.id.personal_center_ll_my_collection:
                //我的收藏页面
                intent = new Intent(PersonalInfoActivity.this, MyCollectionActivity.class);
                startActivity(intent);
                break;

            case R.id.personal_center_ll_shipping_address:
                //收货地址
                intent = new Intent(PersonalInfoActivity.this, ShippingAddressActivity.class);
                startActivity(intent);
                break;

            case R.id.personal_center_ll_update_password:
                //修改密码
                intent = new Intent(PersonalInfoActivity.this, UpdatePasswordActivity.class);
                startActivity(intent);
                break;

            case R.id.personal_center_ll_clear_cache:
                //清理缓存
                clearCache();
                break;

            case R.id.personal_center_ll_about_app:
                //关于高迪app
                intent = new Intent(PersonalInfoActivity.this, AboutAppActivity.class);
                startActivity(intent);
                break;

        }
    }


    @Override
    protected void photoCallBack(String path) {
        BitmapUtils.loadImage(personalCenterIvUserPhoto, path, BitmapUtils.ROUND);
        requestRegisterData(path);
    }

    private void clearCache() {
        if (TextUtils.isEmpty(tvClearCache.getTag().toString()))
            return;

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTopImage(R.mipmap.app_icon);
        builder.setMessage(getString(R.string.ask_clear_cache))
                .setPositiveButton(getString(android.R.string.ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                DataCleanManager.clearAllCache(APP.getInstance());
                                getCacheSize(true);
                                showToast(getString(R.string.clear_cache_done));
                                dialogInterface.dismiss();
                            }
                        }
                ).setNegativeButton(APP.getInstance().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog mDialog = builder.create();
        mDialog.show();
    }

    private void getCacheSize(boolean isClear) {
        try {
            if (isClear) {
                tvClearCache.setText("0M");
                tvClearCache.setTag("");
            } else {
                String totalCacheSize = DataCleanManager.getTotalCacheSize(APP.getInstance());
                tvClearCache.setTag(totalCacheSize);
                tvClearCache.setText(totalCacheSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传用户头像
     */
    private void requestRegisterData(String path) {
        List<File> files = new ArrayList<>();
        files.add(new File(path));
        showWaiting();
        String url = NetworkConstants.SAVE_AVATOR_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        MultipartRequest<CommonListDataResponse> multipartRequest = new MultipartRequest<>(url, CommonListDataResponse.class, "images", files, params,
                new Response.Listener<CommonListDataResponse>() {
                    @Override
                    public void onResponse(CommonListDataResponse response) {
                        dismissWaiting();
                        if (response.isSuccess()) {
                            if (null != Global.user) {
                                for (int i = 0; i < response.getData().size(); i++) {
                                    String path = response.getData().get(i);
                                    Global.user.setAvatar(response.getData().get(i));
                                    BitmapUtils.loadImage(personalCenterIvUserPhoto, path, BitmapUtils.ROUND);
                                }
                                Settings.saveProfile(Global.user);
                                EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_PHPTO_DATA));
                            }
                        } else {
                            showToast(response.getMsg());
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showToast(R.string.generic_check);
                dismissWaiting();
            }
        });
        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 60 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        APP.getInstance().getRequestQueue().add(multipartRequest);
    }

    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.EXIT_ACCOUNT) {
            if (!isExitAccount)
                finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
